package freespiritsocial.io.user.viewmodel

import freespiritsocial.io.user.network.apiService
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.requestNoCheck
import me.hgj.jetpackmvvm.util.MD5Utils

class LoginViewModel: BaseViewModel() {
    val phoneNumber = StringObservableField()
    val countryCode = StringObservableField("+44")
    val password = StringObservableField()

    fun forgotPassword() {
    }

    fun login(success: (token: String) -> Unit) {
        if (password.get().length < 8) {
            toast.postValue("Please enter a password of 8-16 digits.")
            return
        }
        requestNoCheck(
            {
                apiService.login(
                    hashMapOf(
                        "userMobile" to phoneNumber.get().replace(" ",""),
                        "areaCode" to countryCode.get(),
                        "password" to MD5Utils.md5(password.get())
                    )
                )
            },
            { response ->
                response.body()?.let {
                    if (it.isSucces()) {
                        response.headers()["token"]?.let(success)
                    } else
                        toast.postValue(it.message)
                }
            },isShowDialog = true
        )

    }

    fun google(userId: String,loginFail: () -> Unit,loginSuccess: (String) -> Unit) {
        requestNoCheck({
            apiService.signInByThird(
                hashMapOf(
                    "thirdPartyId" to userId,
                    "thirdPartyType" to 2
                )
            )
        },{ response ->
            response.body()?.let {
                when {
                    it.isSucces() -> {
                        response.headers()["token"]?.let(loginSuccess)
                    }
                    it.code == 30000 -> {
                        loginFail()
                    }
                    else -> toast.postValue(it.message)
                }
            }
        },isShowDialog = true)
    }

    fun faceBook(userId: String,loginFail: () -> Unit,loginSuccess: (String) -> Unit) {
        requestNoCheck({
            apiService.signInByThird(
                hashMapOf(
                    "thirdPartyId" to userId,
                    "thirdPartyType" to 3
                )
            )
        },{ response ->
            response.body()?.let {
                when {
                    it.isSucces() -> {
                        response.headers()["token"]?.let(loginSuccess)
                    }
                    it.code == 30000 -> {
                        loginFail()
                    }
                    else -> toast.postValue(it.message)
                }
            }
        },isShowDialog = true)
    }

}
